package cn.minimelon.cushaw.view.platform;

import cn.minimelon.bittermelon.bean.AjaxResult;
import cn.minimelon.bittermelon.bean.LoginUser;
import cn.minimelon.bittermelon.exception.WebException;
import cn.minimelon.bittermelon.solon.BaseController;
import cn.minimelon.bittermelon.utils.JSONUtils;
import cn.minimelon.bittermelon.utils.Melon;
import cn.minimelon.cushaw.entity.SysUser;
import cn.minimelon.cushaw.service.JdbcProperties;
import cn.minimelon.cushaw.model.LoginReq;
import cn.minimelon.cushaw.model.LoginRes;
import cn.minimelon.cushaw.service.SysUserService;
import org.beetl.sql.core.*;
import org.beetl.sql.core.db.MySqlStyle;
import org.beetl.sql.ext.DebugInterceptor;
import org.beetl.sql.gen.SourceBuilder;
import org.beetl.sql.gen.SourceConfig;
import org.beetl.sql.gen.simple.EntitySourceBuilder;
import org.beetl.sql.gen.simple.MDSourceBuilder;
import org.beetl.sql.gen.simple.MapperSourceBuilder;
import org.beetl.sql.gen.simple.SimpleMavenProject;
import org.noear.solon.Solon;
import org.noear.solon.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 登录验证
 *
 * @author hiro
 */
@Controller
@Mapping("common")
public class LoginController extends BaseController {
    private final static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Inject
    SysUserService userService;

    @Inject("${melon.master}")
    JdbcProperties jdbc;

    /**
     * 生成验证码
     */
    @Get
    @Mapping("captchaImage")
    public List<SysUser> getCode() throws IOException {
        return userService.selectUserList();
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @Post
    @Mapping("login")
    public LoginRes login(LoginReq loginBody) {
        if (!"admin".equals(loginBody.getUsername()) || !"123456".equals(loginBody.getPassword())) {
            logger.error(JSONUtils.toJSONString(loginBody));
            throw new WebException("common.error.nameNotMatchPwd", "用户名密码不匹配！");
        }
        LoginRes result = new LoginRes();
        result.setToken("Test");
        LoginUser user = new LoginUser();
        user.setId("user-01");
        user.setName("超级管理员");
        result.setUser(user);
        return result;
    }

    @Post
    @Mapping("logout")
    public AjaxResult<Object> logout(LoginUser loginBody) {
        return Melon.success();
    }

    @Get
    @Mapping("/gen/{tableName}")
    public AjaxResult<Object> genCode(String tableName) {
        if (!Solon.cfg().isDebugMode()) {
            return Melon.error("不允许生成代码");
        }
        ConnectionSource source = ConnectionSourceHelper.getSimple(jdbc.getDriverClassName(), jdbc.getJdbcUrl(), jdbc.getUsername(), jdbc.getPassword());
        // source是唯一必须的参数，其他参数都有默认值
        SQLManagerBuilder builder = new SQLManagerBuilder(source);
        // 设置NameConversion，这里数据库命名采用下划线风格，使用UnderlinedNameConversion
        builder.setNc(new UnderlinedNameConversion());
        // 设置一个拦截器，输出debug日志，包含了sql语句和执行参数，执行时间
        builder.setInters(new Interceptor[]{new DebugInterceptor()});
        // 设置数据库分隔，必须跟数据库一样
        builder.setDbStyle(new MySqlStyle());
        SQLManager sqlManager = builder.build();
        List<SourceBuilder> sourceBuilder = new ArrayList<>();
        sourceBuilder.add(new EntitySourceBuilder());
        sourceBuilder.add(new MapperSourceBuilder());
        sourceBuilder.add(new MDSourceBuilder());
        SourceConfig config = new SourceConfig(sqlManager, sourceBuilder);
        SimpleMavenProject project = new SimpleMavenProject();
        project.setBasePackage("cn.minimelon.test");
        project.setRoot("D:/Z0Temp/minimelon");
        config.gen(tableName, project);
        return Melon.success();
    }

}
